<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/30 0030
 * Time: 14:14
 */

namespace app\data\controller;


use think\Cache;
use think\Db;

class Mind extends Base
{
    public $key = 'CurrencyList';

    //todo 实时获取币种数据数据（6s/次）
    //todo 实时获取币种数据数据（6s/次）
    public function CurrencyList(){
      	$date = date('Hi',time());
      	if($date > '0000'  && $date < '0020')return false;
        $list = Db::name('currency')
            ->where(['pid'=>0])
            ->field('cu_id,title')
            ->select();
        if(!$list)return $this->returnError($this->NoData);
        $SystemPrice = Cache::get('AllCurrencyList');
      	var_dump($SystemPrice);
        $result = [];
        foreach ($list as $k=>$v){
            $list[$k]['son'] = Db::name('currency')
                ->where(['pid'=>$v['cu_id']])
                ->field('cu_id,title')
                ->select();
            foreach ($list[$k]['son'] as $ke=>$va){
                $price = false;
                switch ($v['title']){
                    case 'ZB';
                        $api = 'http://api.zb.cn/data/v1/kline?market='.$va['title'].'_usdt&size=1';
                        $data = json_decode($this->cUrl($api));
                        if(isset($data->data))$price = $data->data[0][3];
                        break;
                    case 'OKEx';
                        $start = str_replace(['+08:00',':'],['Z','%3A'],date(DATE_RFC3339_EXTENDED,time()-3600*12));;
                        $end   = str_replace(['+08:00',':'],['Z','%3A'],date(DATE_RFC3339_EXTENDED,time()));
                        $api = 'https://www.okex.com/api/spot/v3/instruments/'.strtoupper($va['title']).'-USDT/candles?granularity=60&start='.$start.'&end='.$end;
                        $data = json_decode($this->cUrl($api));
                        if(isset($data)) $price = $data[0][4];
                        break;
                    case 'Huobi';
                        $api = "https://api.huobi.pro/market/history/kline?period=60min&size=1&symbol=".$va['title']."usdt";
                        $data = json_decode($this->cUrl($api));
                        if(isset($data->data[0]->close))$price =$data->data[0]->close;
                        break;
                    case 'Binance';
                        $api = 'https://api.binance.com/api/v3/ticker/price?symbol='.strtoupper($va['title']).'USDT';
                        $data = json_decode($this->cUrl($api));
                        if(isset($data->price))$price =$data->price;
                        break;
                    case 'Gate.io';
                        $api = 'https://data.gateio.co/api2/1/candlestick2/'.$va['title'].'_usdt?group_sec=60&range_hour=0.01';
                        $data = json_decode($this->cUrl($api));
                        if(isset($data->data[0][2]))$price =$data->data[0][2];
                        break;
                    default;
                        $price = false;
                        break;
                }
                if(!$price)continue;
                $set = [
                    'title' =>$va['title'],
                    'price' =>$price,
                    'platform'=>$v['title'],
                    'time'  =>time(),
                ];
              	$maps = ['cu_id'=>$va['cu_id']];
              	$ress = Db::name('timelydata')->where($maps)->find();
              	if($ress){
                	Db::name('timelydata')->where($maps)->update($set);
                }else{
                  	$set['cu_id'] = $va['cu_id'];
                	Db::name('timelydata')->insert($set);
                }  
              	$set['cu_id'] = $va['cu_id'];
                array_push($result,$set);     
                $abc = $this->GetMindHeightPerson($SystemPrice,$set);              
                if(!$abc)continue;      
              	
                $map = ['cu_id'=>$va['cu_id'],$abc['type']=>0];             	
                $users = Db::name('height_remind')->where($map)->column('uid');
                if(!$users)continue;
              	var_dump($abc,$users);
                $this->SendMsg($abc,$users,5);
              	Db::name('height_remind')->where(['uid'=>['in',$users]])->update([$abc['type']=>1]);
                $reg_id = $this->GetPushReg($users);
                if($reg_id)$this->PushMsg($abc['content'],$abc['title'],$reg_id);
            }
        }
        $list = $result;
        $this->redis->set($this->key,serialize($list));
        return;
    }
  
  	public function dddddd(){
      	$date = date('Hi',time());
      	if($date > '0000'  && $date < '0020')return 0;
        $list = Db::name('currency')
          	->alias('a')
          	->join('currency b','a.pid = b.cu_id')
            ->where(['a.pid'=>['>',0],'a.type'=>1])
            ->field('a.cu_id,a.title,b.title as platform')
            ->select();
      	//var_dump($list);die;
        if(!$list)return $this->returnError($this->NoData);
        $SystemPrice = Cache::get('AllCurrencyList');
        $result = [];
        foreach ($list as $k=>$v){
          	///var_dump($v);die;
            $price = false;
                switch ($v['platform']){
                    case 'ZB';
                        $api = 'http://api.zb.cn/data/v1/kline?market='.$v['title'].'_usdt&size=1';
                        $data = json_decode($this->cUrl($api));
                        if(isset($data->data))$price = $data->data[0][3];
                    	//if($v['title'] == 'bchabc')var_dump($data);die;
                        break;
                    case 'OKEx';
                        $start = str_replace(['+08:00',':'],['Z','%3A'],date(DATE_RFC3339_EXTENDED,time()-3600*12));;
                        $end   = str_replace(['+08:00',':'],['Z','%3A'],date(DATE_RFC3339_EXTENDED,time()));
                        $api = 'https://www.okex.com/api/spot/v3/instruments/'.strtoupper($v['title']).'-USDT/candles?granularity=60&start='.$start.'&end='.$end;
                        $data = json_decode($this->cUrl($api));
                        if(isset($data)) $price = $data[0][4];
                        break;
                    case 'Huobi';
                        $api = "https://api.huobi.pro/market/history/kline?period=60min&size=1&symbol=".$v['title']."usdt";
                        $data = json_decode($this->cUrl($api));
                        if(isset($data->data[0]->close))$price =$data->data[0]->close;
                        break;
                    case 'Binance';
                        $api = 'https://api.binance.com/api/v3/ticker/price?symbol='.strtoupper($v['title']).'USDT';
                        $data = json_decode($this->cUrl($api));
                        if(isset($data->price))$price =$data->price;
                        break;
                    case 'Gate.io';
                        $api = 'https://data.gateio.co/api2/1/candlestick2/'.$v['title'].'_usdt?group_sec=60&range_hour=0.01';
                        $data = json_decode($this->cUrl($api));
                        if(isset($data->data[0][2]))$price =$data->data[0][2];
                        break;
                    default;
                        $price = false;
                        break;
                }
                if(!$price)continue;
                $set = [
                    'title' =>$v['title'],
                    'price' =>$price,
                    'platform'=>$v['platform'],
                    'time'  =>time(),
                ];
              	$maps = ['cu_id'=>$v['cu_id']];
              	$ress = Db::name('timelydata')->where($maps)->find();
              	if($ress){
                	Db::name('timelydata')->where($maps)->update($set);
                }else{
                  	$set['cu_id'] = $va['cu_id'];
                	Db::name('timelydata')->insert($set);
                }  
              	$set['cu_id'] = $v['cu_id'];
                array_push($result,$set);     
                $abc = $this->GetMindHeightPerson($SystemPrice,$set);       	
                if(!$abc)continue;      
                $map = ['cu_id'=>$v['cu_id'],$abc['type']=>0];             	
                $users = Db::name('height_remind')->where($map)->column('uid');
                if(!$users)continue;
                $this->SendMsg($abc,$users,5);
              	Db::name('height_remind')->where(['uid'=>['in',$users]])->update([$abc['type']=>1]);
                $reg_id = $this->GetPushReg($users);
                if($reg_id)$this->PushMsg($abc['content'],$abc['title'],$reg_id);
        }
        $list = $result;
        $this->redis->set($this->key,serialize($list));
        return;
    }
  

    //todo 高低提醒
    public function GetMindHeightPerson($system,$price){
        $message = Db::name('message_model')->where(['type'=>4])->field('content,title')->select();
        $s3m = $message[0];$s2m = $message[1];$s1m = $message[2];$b3m = $message[5];$b2m = $message[4];$b1m = $message[3];
        $x = Db::name('price_set')->where(['id'=>2])->value('x');
        foreach ($system as $k=>$v){
            if($v['platform'] == $price['platform'] && $v['title'] == $price['title']){
                $ref = ['loss'=>$v['price']/$x,'platform'=>$v['platform'],'title'=>$v['title']];
                if($price['price'] <=$v['buy_3']){
                  	$type = 'b3';
                    $ref['buy_3'] = $v['buy_3'];
                    $content = $b3m['content'];
                    $title = $b3m['title'];
                }elseif($price['price'] <= $v['buy_2']){
                  	$type = 'b2';
                    $ref['buy_2'] = $v['buy_2'];
                    $content = $b2m['content'];
                    $title = $b2m['title'];
                }elseif($price['price'] <= $v['buy_1']){
                  	$type = 'b1';
                    $ref['buy_1'] = $v['buy_1'];
                    $content = $b1m['content'];
                    $title =   $b1m['title'];
                }elseif($price['price'] >= $v['sell_3']){
                  	$type = 's3';
                    $ref['sell_3'] = $v['sell_3'];
                    $content = $s3m['content'];
                    $title = $s3m['title'];
                }elseif($price['price'] >= $v['sell_2']){
                  	$type = 's2';
                    $ref['sell_2'] = $v['sell_2'];
                    $content = $s2m['content'];
                    $title = $s2m['title'];
                }elseif($price['price'] >= $v['sell_1']){
                  	$type = 's1';
                    $ref['sell_1'] = $v['sell_1'];                  	
                    $content = $s1m['content'];
                    $title = $s1m['title'];
                }else{
                    return false;
                }
                $tip = $this->GetMessage($content,$title,$ref);
              	$tip['type'] = $type;
                return $tip;
            }
        }
    }
}